#!/bin/bash
set -e

log=.log.`date +%N`
echo `basename $0` $@ >>$log
prog=`basename $0`
args=$@

while getopts  ":s:w:dp:b:a:" opts
do
	case  $opts  in
	s)
		sample_name=$OPTARG
		;;
	w)
		window=$OPTARG
		;;
	d)
		markdup=true
		;;
	b)
        assembly=$OPTARG
        ;;
	p)
        out_prefix=$OPTARG
        ;;
	a)
        seq_method=$OPTARG
        ;;
	\?)
		echo `basename $0` "[-a seq_method] [-d] [-s sample_name] [-w window_size] [-b asemmbly] <r1.fq> <r2.fq>"
		exit 1
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$2" ]; then
	echo `basename $0` '[-a seq_method] [-d] [-s sample_name] [-w window_size] [-b asemmbly] <r1.fq> <r2.fq>'
	exit 1
fi


makedir=true
if [ -z "$assembly" ]; then
	export assembly=b38
else 
	export assembly
fi


. /mnt/ilustre/app/medical/tools/.var


if [ -z "$window" ]; then
	window=200000
fi

if [ -z "$seq_method" ]; then
	seq_method=malbac
fi

stat.sh -s$sample_name $1 $2 &
sleep $ss
fastqc.sh -s$sample_name $1 $2 &
sleep $ss

if
echo $1 |perl -n -e 'if(/^\//){exit 0;}else{exit 2;}'
then
	if test "$seq_method" = "malbac"; then
	cutadp_malbac.sh $1 $2
	else
	cutadp.sh $1 $2
	fi
else
	if test "$seq_method" = "malbac"; then
	cutadp_malbac.sh ../$1 ../$2
	else
	cutadp.sh ../$1 ../$2
	fi
fi

stat.sh -s$sample_name 1.1.cut.fastq 1.2.cut.fastq &
sleep $ss
fastqc.sh -s$sample_name 1.1.cut.fastq 1.2.cut.fastq &
sleep $ss

align2bam.sh -b $assembly -s $sample_name 1.1.cut.fastq 1.2.cut.fastq

if test "$markdup" = "true"; then

markdup.sh 1.sort.bam


summ_sc_gatk.sh -b38 1.deldup.bam $data_path/intervals/1/cnv_sc/$assembly.rand.site.bed &
sleep $ss
summ_sc_gatk.sh -p2 -b38 1.deldup.bam $data_path/intervals/1/b38.bed && plot_cov.sh 2.sample_summary 2.sample_interval_summary &
sleep $ss

hmmcopyb38.sh -b b38 -w $window 1.deldup.bam #to be continued 


lorenz_rc_cnv.sh 1.deldup.bam &
sleep $ss
fastqc.sh -s$sample_name 1.deldup.bam &
sleep $ss

else

summ_sc_gatk.sh -b38 1.sort.bam $data_path/intervals/1/cnv_sc/$assembly.rand.site.bed &
sleep $ss
summ_sc_gatk.sh -p2 -b38 1.sort.bam $data_path/intervals/1/b38.bed && plot_cov.sh 2.sample_summary 2.sample_interval_summary && csv2xls.pl 2.sample_interval_summary 2.sample_interval_summary.xls &
sleep $ss
hmmcopyb38.sh -b b38 -w $window 1.sort.bam #to be continued 

lorenz_rc_cnv.sh 1.sort.bam &
sleep $ss
fastqc.sh -s$sample_name 1.sort.bam &
sleep $ss
fi


wait

bak.sh -tcnv *.pdf *.html *.q20.txt .log* *summary *.xls

exit 0
